package com.hulk.rpc.transport.client;

import com.hulk.rpc.invoke.InvokerUtils;
import com.hulk.rpc.loadbalance.LoadBalance;
import com.hulk.rpc.loadbalance.Weightable;
import lombok.AllArgsConstructor;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xuxukang
 * @date 2019-04-15 14:53
 */
@AllArgsConstructor
public class MethodRouter {

  private final Method method;
  private final String serviceMethodName;
  private final LoadBalance<Weightable> loadBalance;

  MethodRouter(String serviceMethodName, LoadBalance<Weightable> loadBalance) {
    this.method = InvokerUtils.toMethod(serviceMethodName);
    this.serviceMethodName = serviceMethodName;
    this.loadBalance = loadBalance;
  }

  void setConnectors(Collection<NettyClientContext> connectors) {
    if (connectors == null || connectors.size() == 0) {
      loadBalance.refreshResources(Collections.emptyList());
      return;
    }

    List<Weightable> resources = connectors.stream()
            .filter(t -> t.isSupport(serviceMethodName))
            .collect(Collectors.toList());

    loadBalance.refreshResources(resources);
  }

  public Method getMethod() {
    return method;
  }

  public String getServiceMethodName() {
    return serviceMethodName;
  }

  public NettyClientContext selectConnector() {
    return (NettyClientContext) loadBalance.select();
  }
}
